package com.henu.art.aspect;

import com.henu.art.annotation.IgnoreExceptionHandler;
import com.henu.art.util.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
@SuppressWarnings("all")
public class GlobalExceptionHandlerAspect {

    @Around("execution(* com.henu.art.controller..*(..))")
    public Object handleException(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            if (shouldIgnoreExceptionHandling(joinPoint)) {
                return joinPoint.proceed();
            }
            return joinPoint.proceed();
        } catch (Exception e) {
            return Result.Exception(e.getMessage());
        }
    }

    private boolean shouldIgnoreExceptionHandling(ProceedingJoinPoint joinPoint) {
        if (joinPoint.getSignature() instanceof org.aspectj.lang.reflect.MethodSignature) {
            org.aspectj.lang.reflect.MethodSignature methodSignature = (org.aspectj.lang.reflect.MethodSignature) joinPoint.getSignature();
            if (methodSignature.getMethod().isAnnotationPresent(IgnoreExceptionHandler.class)) {
                return true;
            }
        }
        return joinPoint.getTarget().getClass().isAnnotationPresent(IgnoreExceptionHandler.class);
    }
}
